﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Management;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Collections;
using System.Diagnostics;
using System.Data.SqlClient;
using Microsoft.VisualBasic.CompilerServices;
using System.ServiceProcess;

namespace BizTool
{
    class Program
    {
        static void Main(string[] args)
        {

            #region ResumableWithErrorDescription
            string errorDescrList = ConfigurationManager.AppSettings["ResumableMessages_ErrorDescription"];
            string[] values1 = errorDescrList.Split(',');
            foreach (string data in values1)
            {
                if (data.Length > 0)
                {
                    ResumeSvcInstByOrchestrationErrDescName(data);
                }
            }
            #endregion

            #region ResumableWithSendPortName
            string errorURLList = ConfigurationManager.AppSettings["ResumableMessages_SendPort"];
            string[] values2 = errorURLList.Split(',');
            foreach (string data in values2)
            {
                if (data.Length > 0)
                {
                    ResumeSvcInstBySendPortName(data);
                }
            }
            #endregion

            #region ResumableWithOrchestrationName
            string errorOrchList = ConfigurationManager.AppSettings["ResumableMessages_OrchestrationName"];
            string[] values3 = errorOrchList.Split(',');
            foreach (string data in values3)
            {
                if (data.Length > 0)
                {
                    ResumeSvcInstByOrchestrationName(data);
                }
            }
            #endregion

            #region TerminateWithErrorDescription
            string errorDescrList1 = ConfigurationManager.AppSettings["TerminateMessages_ErrorDescription"];
            string[] values11 = errorDescrList1.Split(',');
            foreach (string data in values11)
            {
                if (data.Length > 0)
                {
                    TerminateSvcInstByErrDescName(data);
                }
            }
            #endregion

            #region TerminateWithSendPortName
            string errorURLList1 = ConfigurationManager.AppSettings["TerminateMessages_SendPort"];
            string[] values21 = errorURLList1.Split(',');
            foreach (string data in values21)
            {
                if (data.Length > 0)
                {
                    TerminateSvcInstBySendPortName(data);
                }
            }
            #endregion

            #region TerminateWithOrchestrationName
            string errorOrchList1 = ConfigurationManager.AppSettings["TerminateMessages_OrchestrationName"];
            string[] values31 = errorOrchList1.Split(',');
            foreach (string data in values31)
            {
                if (data.Length > 0)
                {
                    TerminateSvcInstByOrchestrationName(data);
                }
            }
            #endregion

            #region HostInstances
            string IgnoreHostList = ConfigurationManager.AppSettings["Ignorable_HostInstance"];
            string[] values4 = IgnoreHostList.Split(',');
            EnumerateAndStart(values4);
            #endregion

            #region SendPorts
            string IgnoreSendPortList = ConfigurationManager.AppSettings["Ignorable_SendPorts"];
            string[] values5 = IgnoreSendPortList.Split(',');
            StartSendPorts(values5);
            #endregion

            #region ReceiveLocation
            string IgnoreRcvLocationList = ConfigurationManager.AppSettings["Ignorable_ReceiveLocations"];
            string[] values6 = IgnoreRcvLocationList.Split(',');
            StartReceivePorts(values6);
            #endregion

            #region Orchestrations
            string IgnoreOrchestrationList = ConfigurationManager.AppSettings["Ignorable_Orchestrations"];
            string[] values7 = IgnoreOrchestrationList.Split(',');
            StartOrchestrations(values7);
            #endregion

            SendFailureReport();


        }
        static ArrayList StoreServiceName = new ArrayList();
        static ArrayList StoreErrorDescription = new ArrayList();
        static ArrayList ReceiveLocationStatus = new ArrayList();
        static ArrayList OrchestrationStatus = new ArrayList();
        static ArrayList SendPortStatus = new ArrayList();
        static ArrayList HostStatus = new ArrayList();
        static string BizTalkServer = ConfigurationManager.AppSettings["BizTalkServer"].ToString();
        // Resuming the Suspended Messages using Error Description name
        public static void ResumeSvcInstByOrchestrationErrDescName(string strOrchestrationErrDesc)
        {
            try
            {
                const uint SERVICE_CLASS_ORCHESTRATION = 1;
                const uint SERVICE_STATUS_SUSPENDED_RESUMABLE = 4;
                const uint REGULAR_RESUME_MODE = 1;

                string strWQL = string.Format(
                    "SELECT * FROM MSBTS_ServiceInstance WHERE ServiceClass = {0} AND ServiceStatus = {1} AND ErrorDescription like \"%{2}%\"",
                    SERVICE_CLASS_ORCHESTRATION.ToString(), SERVICE_STATUS_SUSPENDED_RESUMABLE.ToString(), strOrchestrationErrDesc);

                ManagementObjectSearcher searcherServiceInstance = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strWQL), null);
                int nNumSvcInstFound = searcherServiceInstance.Get().Count;

                // If we found any
                if (nNumSvcInstFound > 0)
                {
                    // Construct ID arrays to be passed into ResumeServiceInstancesByID() method
                    string[] InstIdList = new string[nNumSvcInstFound];
                    string[] ClassIdList = new string[nNumSvcInstFound];
                    string[] TypeIdList = new string[nNumSvcInstFound];

                    string strHost = string.Empty;
                    string strReport = string.Empty;
                    int i = 0;
                    foreach (ManagementObject objServiceInstance in searcherServiceInstance.Get())
                    {
                        // It is safe to assume that all service instances belong to a single Host.
                        if (strHost == string.Empty)
                            strHost = objServiceInstance["HostName"].ToString();

                        ClassIdList[i] = objServiceInstance["ServiceClassId"].ToString();
                        TypeIdList[i] = objServiceInstance["ServiceTypeId"].ToString();
                        InstIdList[i] = objServiceInstance["InstanceID"].ToString();

                        strReport += string.Format("  {0}\n", objServiceInstance["InstanceID"].ToString());
                        i++;
                    }

                    // Load the MSBTS_HostQueue with Host name and invoke the "ResumeServiceInstancesByID" method
                    string strHostQueueFullPath = string.Format(string.Concat(BizTalkServer, ":MSBTS_HostQueue.HostName=\"{0}\""), strHost);
                    ManagementObject objHostQueue = new ManagementObject(strHostQueueFullPath);

                    objHostQueue.InvokeMethod("ResumeServiceInstancesByID",
                        new object[] { ClassIdList, TypeIdList, InstIdList, REGULAR_RESUME_MODE }
                    );
                    Console.WriteLine(string.Format("Service instances with the following service instance IDs have been resumed:\n{0}", strReport));
                }
                else
                {
                    System.Console.WriteLine(string.Format("There is no suspended (resumable) service instance found for orchestration '{0}'.", strOrchestrationErrDesc));
                }
            }
            catch (Exception excep)
            {
                Console.WriteLine("Error: " + excep.Message);
            }
        }

        // Resuming the Suspended Messages using Orchestration name
        public static void ResumeSvcInstByOrchestrationName(string strOrchestrationName)
        {
            try
            {
                const uint SERVICE_CLASS_ORCHESTRATION = 1;
                const uint SERVICE_STATUS_SUSPENDED_RESUMABLE = 4;
                const uint REGULAR_RESUME_MODE = 1;

                string strWQL = string.Format(
                    "SELECT * FROM MSBTS_ServiceInstance WHERE ServiceClass = {0} AND ServiceStatus = {1} AND ServiceName = \"{2}\"",
                    SERVICE_CLASS_ORCHESTRATION.ToString(), SERVICE_STATUS_SUSPENDED_RESUMABLE.ToString(), strOrchestrationName);

                ManagementObjectSearcher searcherServiceInstance = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strWQL), null);
                int nNumSvcInstFound = searcherServiceInstance.Get().Count;

                // If we found any
                if (nNumSvcInstFound > 0)
                {
                    // Construct ID arrays to be passed into ResumeServiceInstancesByID() method
                    string[] InstIdList = new string[nNumSvcInstFound];
                    string[] ClassIdList = new string[nNumSvcInstFound];
                    string[] TypeIdList = new string[nNumSvcInstFound];

                    string strHost = string.Empty;
                    string strReport = string.Empty;
                    int i = 0;
                    foreach (ManagementObject objServiceInstance in searcherServiceInstance.Get())
                    {
                        // It is safe to assume that all service instances belong to a single Host.
                        if (strHost == string.Empty)
                            strHost = objServiceInstance["HostName"].ToString();

                        ClassIdList[i] = objServiceInstance["ServiceClassId"].ToString();
                        TypeIdList[i] = objServiceInstance["ServiceTypeId"].ToString();
                        InstIdList[i] = objServiceInstance["InstanceID"].ToString();

                        strReport += string.Format("  {0}\n", objServiceInstance["InstanceID"].ToString());
                        i++;
                    }

                    // Load the MSBTS_HostQueue with Host name and invoke the "ResumeServiceInstancesByID" method
                    string strHostQueueFullPath = string.Format(string.Concat(BizTalkServer, ":MSBTS_HostQueue.HostName=\"{0}\""), strHost);
                    ManagementObject objHostQueue = new ManagementObject(strHostQueueFullPath);

                    objHostQueue.InvokeMethod("ResumeServiceInstancesByID",
                        new object[] { ClassIdList, TypeIdList, InstIdList, REGULAR_RESUME_MODE }
                    );

                    Console.WriteLine(string.Format("Service instances with the following service instance IDs have been resumed:\n{0}", strReport));
                }
                else
                {
                    System.Console.WriteLine(string.Format("There is no suspended (resumable) service instance found for orchestration '{0}'.", strOrchestrationName));
                }
            }
            catch (Exception excep)
            {
                Console.WriteLine("Error: " + excep.Message);
            }
        }

        // Resuming the Suspended Messages through SendPort name
        public static void ResumeSvcInstBySendPortName(string strOutboundURL)
        {
            try
            {
                const uint SERVICE_STATUS_SUSPENDED_RESUMABLE = 4;
                const uint REGULAR_RESUME_MODE = 1;

                string strSendPortWQL = string.Format(
                   "SELECT * FROM MSBTS_SendPort WHERE Name = \"{0}\"",
                   strOutboundURL);

                ManagementObjectSearcher searcherSendPort = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strSendPortWQL), null);
                int nNumSendPortFound = searcherSendPort.Get().Count;

                if (nNumSendPortFound > 0)
                {
                    bool fSvcInstFound = false;

                    // For each associating send port that we found
                    foreach (ManagementObject objSendPort in searcherSendPort.Get())
                    {
                        // Construct the WQL to find suspended service instance associating with the send port
                        string strSvcInstWQL = string.Format(
                           "SELECT * FROM MSBTS_ServiceInstance WHERE ServiceStatus = {0} AND ServiceName = \"{1}\"",
                           SERVICE_STATUS_SUSPENDED_RESUMABLE.ToString(), objSendPort["Name"]);

                        ManagementObjectSearcher searcherServiceInstance = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strSvcInstWQL), null);
                        int nNumSvcInstFound = searcherServiceInstance.Get().Count;

                        // If we found any matching suspended service instance(s)
                        if (nNumSvcInstFound > 0)
                        {
                            fSvcInstFound = true;

                            // Construct ID arrays to be passed into ResumeServiceInstancesByID() method
                            string[] InstIdList = new string[nNumSvcInstFound];
                            string[] ClassIdList = new string[nNumSvcInstFound];
                            string[] TypeIdList = new string[nNumSvcInstFound];

                            string strHost = string.Empty;
                            string strReport = string.Empty;
                            int i = 0;
                            foreach (ManagementObject objServiceInstance in searcherServiceInstance.Get())
                            {
                                // It is safe to assume that all service instances of a send port belong to a single Host.
                                if (strHost == string.Empty)
                                    strHost = objServiceInstance["HostName"].ToString();

                                ClassIdList[i] = objServiceInstance["ServiceClassId"].ToString();
                                TypeIdList[i] = objServiceInstance["ServiceTypeId"].ToString();
                                InstIdList[i] = objServiceInstance["InstanceID"].ToString();

                                strReport += string.Format("  {0}\n", objServiceInstance["InstanceID"].ToString());
                                i++;
                            }

                            // Load the MSBTS_HostQueue with Host name and invoke the "ResumeServiceInstancesByID" method
                            string strHostQueueFullPath = string.Format(string.Concat(BizTalkServer, ":MSBTS_HostQueue.HostName=\"{0}\""), strHost);
                            ManagementObject objHostQueue = new ManagementObject(strHostQueueFullPath);

                            objHostQueue.InvokeMethod("ResumeServiceInstancesByID",
                               new object[] { ClassIdList, TypeIdList, InstIdList, REGULAR_RESUME_MODE }
                               );

                            Console.WriteLine(string.Format("Service instances with the following service instance IDs have been resumed:\n{0}", strReport));
                        }
                    }
                    if (!fSvcInstFound)
                    {
                        System.Console.WriteLine(string.Format("There is no suspended (resumable) service instance associating with outbound URL '{0}'.", strOutboundURL));
                    }
                }
                else
                {
                    System.Console.WriteLine(string.Format("There is no send port associating with outbound URL '{0}'.", strOutboundURL));
                }
            }
            catch (Exception excep)
            {
                Console.WriteLine("Error: " + excep.Message);
            }
        }

        public static void TerminateSvcInstByErrDescName(string strOrchestrationErrDesc)
        {
            try
            {
                const uint SERVICE_STATUS_SUSPENDED_NONRESUMABLE = 32;

                string strWQL = string.Format(
                    "SELECT * FROM MSBTS_ServiceInstance WHERE ServiceStatus = {0} AND ErrorDescription like \"%{1}%\"",
                     SERVICE_STATUS_SUSPENDED_NONRESUMABLE.ToString(), strOrchestrationErrDesc);

                ManagementObjectSearcher searcherServiceInstance = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strWQL), null);
                int nNumSvcInstFound = searcherServiceInstance.Get().Count;

                // If we found any
                if (nNumSvcInstFound > 0)
                {
                    // Construct ID arrays to be passed into ResumeServiceInstancesByID() method
                    string[] InstIdList = new string[nNumSvcInstFound];
                    string[] ClassIdList = new string[nNumSvcInstFound];
                    string[] TypeIdList = new string[nNumSvcInstFound];

                    string strHost = string.Empty;
                    string strReport = string.Empty;
                    int i = 0;
                    foreach (ManagementObject objServiceInstance in searcherServiceInstance.Get())
                    {
                        // It is safe to assume that all service instances belong to a single Host.
                        if (strHost == string.Empty)
                            strHost = objServiceInstance["HostName"].ToString();

                        ClassIdList[i] = objServiceInstance["ServiceClassId"].ToString();
                        TypeIdList[i] = objServiceInstance["ServiceTypeId"].ToString();
                        InstIdList[i] = objServiceInstance["InstanceID"].ToString();

                        strReport += string.Format("  {0}\n", objServiceInstance["InstanceID"].ToString());
                        i++;
                    }

                    // Load the MSBTS_HostQueue with Host name and invoke the "ResumeServiceInstancesByID" method

                    string strHostQueueFullPath = string.Format(string.Concat(BizTalkServer, ":MSBTS_HostQueue.HostName=\"{0}\""), strHost);
                    ManagementObject objHostQueue = new ManagementObject(strHostQueueFullPath);

                    objHostQueue.InvokeMethod("TerminateServiceInstancesByID",
                        new object[] { ClassIdList, TypeIdList, InstIdList }
                    );

                    Console.WriteLine(string.Format("Service instances with the following service instance IDs have been terminated:\n{0}", strReport));
                }
                else
                {
                    System.Console.WriteLine(string.Format("There is no suspended (resumable) service instance found for orchestration '{0}'.", strOrchestrationErrDesc));
                }
            }
            catch (Exception excep)
            {
                Console.WriteLine("Error: " + excep.Message);
            }
        }

        // Resuming the Suspended Messages using Orchestration name
        public static void TerminateSvcInstByOrchestrationName(string strOrchestrationName)
        {
            try
            {
                const uint SERVICE_CLASS_ORCHESTRATION = 1;
                const uint SERVICE_STATUS_SUSPENDED_NONRESUMABLE = 32;

                string strWQL = string.Format(
                    "SELECT * FROM MSBTS_ServiceInstance WHERE ServiceClass = {0} AND ServiceStatus = {1} AND ServiceName = \"{2}\"",
                    SERVICE_CLASS_ORCHESTRATION.ToString(), SERVICE_STATUS_SUSPENDED_NONRESUMABLE.ToString(), strOrchestrationName);

                ManagementObjectSearcher searcherServiceInstance = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strWQL), null);
                int nNumSvcInstFound = searcherServiceInstance.Get().Count;

                // If we found any
                if (nNumSvcInstFound > 0)
                {
                    // Construct ID arrays to be passed into ResumeServiceInstancesByID() method
                    string[] InstIdList = new string[nNumSvcInstFound];
                    string[] ClassIdList = new string[nNumSvcInstFound];
                    string[] TypeIdList = new string[nNumSvcInstFound];

                    string strHost = string.Empty;
                    string strReport = string.Empty;
                    int i = 0;
                    foreach (ManagementObject objServiceInstance in searcherServiceInstance.Get())
                    {
                        // It is safe to assume that all service instances belong to a single Host.
                        if (strHost == string.Empty)
                            strHost = objServiceInstance["HostName"].ToString();

                        ClassIdList[i] = objServiceInstance["ServiceClassId"].ToString();
                        TypeIdList[i] = objServiceInstance["ServiceTypeId"].ToString();
                        InstIdList[i] = objServiceInstance["InstanceID"].ToString();

                        strReport += string.Format("  {0}\n", objServiceInstance["InstanceID"].ToString());
                        i++;
                    }

                    // Load the MSBTS_HostQueue with Host name and invoke the "ResumeServiceInstancesByID" method
                    string strHostQueueFullPath = string.Format(string.Concat(BizTalkServer, ":MSBTS_HostQueue.HostName=\"{0}\""), strHost);
                    ManagementObject objHostQueue = new ManagementObject(strHostQueueFullPath);

                    objHostQueue.InvokeMethod("TerminateServiceInstancesByID",
                        new object[] { ClassIdList, TypeIdList, InstIdList }
                    );

                    Console.WriteLine(string.Format("Service instances with the following service instance IDs have been terminated:\n{0}", strReport));
                }
                else
                {
                    System.Console.WriteLine(string.Format("There is no  service instance found for orchestration '{0}'.", strOrchestrationName));
                }
            }
            catch (Exception excep)
            {
                Console.WriteLine("Error: " + excep.Message);
            }
        }

        // Resuming the Suspended Messages through SendPort name
        public static void TerminateSvcInstBySendPortName(string strOutboundURL)
        {
            try
            {
                const uint SERVICE_STATUS_SUSPENDED_NONRESUMABLE = 32;

                string strSendPortWQL = string.Format(
                   "SELECT * FROM MSBTS_SendPort WHERE Name = \"{0}\"",
                   strOutboundURL);

                ManagementObjectSearcher searcherSendPort = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strSendPortWQL), null);
                int nNumSendPortFound = searcherSendPort.Get().Count;

                if (nNumSendPortFound > 0)
                {
                    bool fSvcInstFound = false;

                    // For each associating send port that we found
                    foreach (ManagementObject objSendPort in searcherSendPort.Get())
                    {
                        // Construct the WQL to find suspended service instance associating with the send port
                        string strSvcInstWQL = string.Format(
                           "SELECT * FROM MSBTS_ServiceInstance WHERE ServiceStatus = {0} AND ServiceName = \"{1}\"",
                           SERVICE_STATUS_SUSPENDED_NONRESUMABLE.ToString(), objSendPort["Name"]);

                        ManagementObjectSearcher searcherServiceInstance = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strSvcInstWQL), null);
                        int nNumSvcInstFound = searcherServiceInstance.Get().Count;

                        // If we found any matching suspended service instance(s)
                        if (nNumSvcInstFound > 0)
                        {
                            fSvcInstFound = true;

                            // Construct ID arrays to be passed into ResumeServiceInstancesByID() method
                            string[] InstIdList = new string[nNumSvcInstFound];
                            string[] ClassIdList = new string[nNumSvcInstFound];
                            string[] TypeIdList = new string[nNumSvcInstFound];

                            string strHost = string.Empty;
                            string strReport = string.Empty;
                            int i = 0;
                            foreach (ManagementObject objServiceInstance in searcherServiceInstance.Get())
                            {
                                // It is safe to assume that all service instances of a send port belong to a single Host.
                                if (strHost == string.Empty)
                                    strHost = objServiceInstance["HostName"].ToString();

                                ClassIdList[i] = objServiceInstance["ServiceClassId"].ToString();
                                TypeIdList[i] = objServiceInstance["ServiceTypeId"].ToString();
                                InstIdList[i] = objServiceInstance["InstanceID"].ToString();

                                strReport += string.Format("  {0}\n", objServiceInstance["InstanceID"].ToString());
                                i++;
                            }

                            // Load the MSBTS_HostQueue with Host name and invoke the "ResumeServiceInstancesByID" method
                            string strHostQueueFullPath = string.Format(string.Concat(BizTalkServer, ":MSBTS_HostQueue.HostName=\"{0}\""), strHost);
                            ManagementObject objHostQueue = new ManagementObject(strHostQueueFullPath);

                            objHostQueue.InvokeMethod("TerminateServiceInstancesByID",
                               new object[] { ClassIdList, TypeIdList, InstIdList }
                               );

                            Console.WriteLine(string.Format("Service instances with the following service instance IDs have been terminated:\n{0}", strReport));
                        }
                    }
                    if (!fSvcInstFound)
                    {
                        System.Console.WriteLine(string.Format("There is no service instance associating with outbound URL '{0}'.", strOutboundURL));
                    }
                }
                else
                {
                    System.Console.WriteLine(string.Format("There is no send port associating with outbound URL '{0}'.", strOutboundURL));
                }
            }
            catch (Exception excep)
            {
                Console.WriteLine("Error: " + excep.Message);
            }
        }

        // Below Code Is To Start The Stopped Host Instances
        public static void EnumerateAndStart(Array data)
        {
            try
            {
                bool flag = true;
                //Create EnumerationOptions and run wql query
                EnumerationOptions enumOptions = new EnumerationOptions();
                enumOptions.ReturnImmediately = false;
                //Search for all HostInstances of 'InProcess' type in the Biztalk namespace scope
                ManagementObjectSearcher searchObject = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_HostInstance where HostType=1", enumOptions);

                //Enumerate through the result set and start each HostInstance if it is already stopped
                foreach (ManagementObject inst in searchObject.Get())
                {
                    foreach (string value in data)
                    {
                        flag = true;
                        if ((inst["HostName"].ToString() == value))
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                    {
                        //Check if ServiceState is 'Stopped'
                        if (inst["ServiceState"].ToString() == "1")
                        {
                            HostStatus.Add(inst["HostName"].ToString());
                            inst.InvokeMethod("Start", null);
                        }
                    }
                }

                Console.WriteLine("HostInstances started successfully");
                return;
            }
            catch (Exception excep)
            {
                Console.WriteLine("Failure while starting HostInstances - " + excep.Message);
            }
        }

        // Code to Start the Send Ports
        public static void StartSendPorts(Array data)
        {
            bool flag = true;
            EnumerationOptions enumOptions = new EnumerationOptions();
            enumOptions.ReturnImmediately = false;
            //Search for all SendPorts      
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_SendPort", enumOptions);

            //Enumerate through the result set and start each Send Port if it is  stopped
            foreach (ManagementObject inst in searchObject.Get())
            {
                foreach (string value in data)
                {
                    flag = true;
                    if ((inst["Name"].ToString() == value))
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    //Check if Status is 'Stopped'
                    if (inst["Status"].ToString() == "1")
                    {
                        SendPortStatus.Add(inst["Name"].ToString() + "," + "UnEnlisted");
                        inst.InvokeMethod("Start", null);
                    }
                    if (inst["Status"].ToString() == "2")
                    {
                        SendPortStatus.Add(inst["Name"].ToString() + "," + "Stopped");
                        inst.InvokeMethod("Start", null);
                    }
                }
            }
            Console.WriteLine("SendPorts were started successfully");
        }

        // Code to Start the Receive Ports
        public static void StartReceivePorts(Array data)
        {
            try
            {
                bool flag = true;
                EnumerationOptions enumOptions = new EnumerationOptions();
                enumOptions.ReturnImmediately = false;
                //Search for all ReceiveLocation        
                ManagementObjectSearcher searchObject = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_ReceiveLocation where IsDisabled = true", enumOptions);

                //Enumerate through the result set and start each ReceiveLocation if it is stopped
                foreach (ManagementObject inst in searchObject.Get())
                {
                    foreach (string value in data)
                    {
                        flag = true;
                        if ((inst["Name"].ToString() == value))
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag && (inst["AdapterName"].ToString() != "Schedule"))
                    {
                        ReceiveLocationStatus.Add(inst["Name"].ToString());
                        inst.InvokeMethod("Enable", null);
                    }
                }
                Console.WriteLine("Receive Locations were started successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        //Code to Start the Orchestrations
        public static void StartOrchestrations(Array data)
        {
            bool flag = true;
            EnumerationOptions enumOptions = new EnumerationOptions();
            enumOptions.ReturnImmediately = false;
            //Search for all SendPorts      
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_Orchestration", enumOptions);

            //Enumerate through the result set and start each Send Port if it is  stopped
            foreach (ManagementObject inst in searchObject.Get())
            {
                foreach (string value in data)
                {
                    flag = true;
                    string testValue = inst["AssemblyName"].ToString() + "." + value;
                    if ((inst["Name"].ToString() == testValue))
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    //Check if Status is 'Stopped'
                    if (inst["OrchestrationStatus"].ToString() == "2")
                    {
                        OrchestrationStatus.Add(inst["Name"].ToString() + "," + "UnEnlisted");
                        inst.InvokeMethod("Enlist", null);
                        inst.InvokeMethod("Start", null);
                    }
                    if (inst["OrchestrationStatus"].ToString() == "3")
                    {
                        OrchestrationStatus.Add(inst["Name"].ToString() + "," + "Stopped");
                        inst.InvokeMethod("Start", null);
                    }
                }
            }
            Console.WriteLine("Orchestrations were started successfully");
        }

        // Code to Send Email
        public static byte[] GetData()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html><head><style>#header {background-color:#228B22;color:white;text-indent:100px;padding:0.0005px;width:900px;}table, th, td {border: 1px solid black;border-collapse: collapse;}th, td {padding: 5px;text-align: left;}#footer { background-color:black;color:white;clear:both;text-align:center;padding:5px;width:900px;</style></head><body><img src=\"http://www.effective-data.com/sites/default/files/styles/software_landing_logo_300/public/app_logo_biztalk_01.png?itok=CWrfBC1b\" alt=\"some_text\" style=\"float:left;width:200px;height:110px;\"><div id=\"header\"><h2>BizTalk Automation Tool Report</h2><h4><p style=\"text-align:right\">Server Name :-");
            sb.AppendLine(Environment.MachineName.ToString());
            sb.AppendLine("</p><p style=\"text-align:right\">Date :- ");
            sb.AppendLine(System.DateTime.Now.ToString());
            sb.AppendLine("</p></h4></div><h3 style=\"color:#B22222\">Please find the status of BizTalk Artifacts Below :-</h3><table style=\"width:250px;align:right;\"><tr><th>CPU Utilization</th>");
            float cpu = getCPUCounter();
            if (cpu > 90)
            {
                sb.AppendLine("<th style=\"background-color:red;color:white\">");
                sb.AppendLine(cpu.ToString() + "%");
            }
            else if (cpu > 70)
            {
                sb.AppendLine("<th style=\"background-color:orange;color:white\">");
                sb.AppendLine(cpu.ToString() + "%");
            }
            else
            {
                sb.AppendLine("<th style=\"background-color:green;color:white\">");
                sb.AppendLine(cpu.ToString() + "%");
            }
            sb.AppendLine("</th></tr></table>");
            EnumerationOptions enumOptions = new EnumerationOptions();
            enumOptions.ReturnImmediately = false;
            ManagementObjectSearcher searchRcv = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_ReceiveLocation where IsDisabled = true", enumOptions);
            int nNumRcv = searchRcv.Get().Count;
            if (nNumRcv > 0 || ReceiveLocationStatus.Count > 0)
            {
                sb.AppendLine("<h4 style=\"color:#6495ED\">Status Of Receive Locations</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Receive Location Name</th><th>Previous Status</th><th>Current Status</th></tr>");
            }
            int i = 1;
            foreach (ManagementObject inst in searchRcv.Get())
            {
                sb.AppendLine("<tr><td style=\"width:50px\">");
                sb.AppendLine(i.ToString());
                sb.AppendLine("</td><td  style=\"width:600px\">");
                sb.AppendLine(inst["Name"].ToString());
                sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                sb.AppendLine("Disabled");
                sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                sb.AppendLine("Disabled");
                sb.AppendLine("</td><tr>");
                i++;
            }
            int rcv = i;
            bool Rcvflag = true;
            foreach (string record in ReceiveLocationStatus)
            {
                foreach (ManagementObject inst in searchRcv.Get())
                {
                    if (record == inst["Name"].ToString())
                    {
                        Rcvflag = false;
                    }
                }
                if (Rcvflag)
                {
                    sb.AppendLine("<tr><td style=\"width:50px\">");
                    sb.AppendLine(rcv.ToString());
                    sb.AppendLine("</td><td style=\"width:600px\">");
                    sb.AppendLine(record);
                    sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine("Disabled</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine("Enabled");
                    sb.AppendLine("</td><tr>");
                    rcv++;
                }
                Rcvflag = true;
            }
            if (ConfigurationManager.AppSettings["FullReport"].ToString() == "Yes")
            {
                if (nNumRcv == 0 && ReceiveLocationStatus.Count == 0)
                {
                    sb.AppendLine("<h4 style=\"color:#6495ED\">Status Of Receive Locations</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Receive Location Name</th><th>Previous Status</th><th>Current Status</th></tr>");
                }
                ManagementObjectSearcher searchRcvFull = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_ReceiveLocation where IsDisabled = false", enumOptions);
                int nNumRcvFull = searchRcvFull.Get().Count;
                if (nNumRcvFull > 0)
                {
                    int rcvFull = rcv;
                    foreach (ManagementObject inst in searchRcvFull.Get())
                    {
                        if (!(ReceiveLocationStatus.Contains(inst["Name"].ToString())))
                        {
                            sb.AppendLine("<tr><td style=\"width:50px\">");
                            sb.AppendLine(rcvFull.ToString());
                            sb.AppendLine("</td><td style=\"width:600px\">");
                            sb.AppendLine(inst["Name"].ToString());
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Enabled");
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Enabled");
                            sb.AppendLine("</td><tr>");
                            rcvFull++;
                        }
                    }
                }
            }
            ManagementObjectSearcher searchSend = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_SendPort where Status <> '3'", enumOptions);
            int j = 1;
            int nNumSnd = searchSend.Get().Count;
            if (nNumSnd > 0 || SendPortStatus.Count > 0)
            {
                sb.AppendLine("</table><h4 style=\"color:#6495ED\">Status Of Send Ports</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Send Port Name</th><th>Previous Status</th><th>Current Status</th></tr>");
            }
            foreach (ManagementObject inst in searchSend.Get())
            {
                sb.AppendLine("<tr><td style=\"width:50px\">");
                sb.AppendLine(j.ToString());
                sb.AppendLine("</td><td style=\"width:600px\">");
                sb.AppendLine(inst["Name"].ToString());
                sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                if (inst["Status"].ToString() == "1") { sb.AppendLine("UnEnlisted"); }
                if (inst["Status"].ToString() == "2") { sb.AppendLine("Stopped"); }
                sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                if (inst["Status"].ToString() == "1") { sb.AppendLine("UnEnlisted"); }
                if (inst["Status"].ToString() == "2") { sb.AppendLine("Stopped"); }
                sb.AppendLine("</td><tr>");
                j++;
            }
            int snd = j;
            bool sndFlag = true;
            foreach (string record in SendPortStatus)
            {
                foreach (ManagementObject inst in searchSend.Get())
                {
                    if (record.Split(',')[0] == inst["Name"].ToString())
                    {
                        sndFlag = false;
                    }
                }
                if (sndFlag)
                {
                    sb.AppendLine("<tr><td style=\"width:50px\">");
                    sb.AppendLine(snd.ToString());
                    sb.AppendLine("</td><td style=\"width:600px\">");
                    sb.AppendLine(record.Split(',')[0]);
                    sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine(record.Split(',')[1]);
                    sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine("Started");
                    sb.AppendLine("</td><tr>");
                    snd++;
                }
                sndFlag = true;
            }
            if (ConfigurationManager.AppSettings["FullReport"].ToString() == "Yes")
            {
                if (nNumSnd == 0 && SendPortStatus.Count == 0)
                {
                    sb.AppendLine("</table><h4 style=\"color:#6495ED\">Status Of Send Ports</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Send Port Name</th><th>Previous Status</th><th>Current Status</th></tr>");
                }
                ManagementObjectSearcher searchSendFull = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_SendPort where Status = '3'", enumOptions);
                int sndFull = snd;
                int nNumSndFull = searchSendFull.Get().Count;
                ArrayList sendprtName = new ArrayList();
                foreach (string record in SendPortStatus)
                {
                    sendprtName.Add(record.Split(',')[0]);
                }
                if (nNumSndFull > 0)
                {
                    foreach (ManagementObject inst in searchSendFull.Get())
                    {
                        if (!(sendprtName.Contains(inst["Name"].ToString())))
                        {
                            sb.AppendLine("<tr><td style=\"width:50px\">");
                            sb.AppendLine(sndFull.ToString());
                            sb.AppendLine("</td><td style=\"width:600px\">");
                            sb.AppendLine(inst["Name"].ToString());
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Started");
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Started");
                            sb.AppendLine("</td><tr>");
                            sndFull++;
                        }
                    }
                }
            }
            ManagementObjectSearcher searchOrch = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_Orchestration where OrchestrationStatus <> '4'", enumOptions);
            int b = 1;
            int nNumOrch = searchOrch.Get().Count;
            if (nNumOrch > 0 || OrchestrationStatus.Count > 0)
            {
                sb.AppendLine("</table><h4 style=\"color:#6495ED\">Status Of Orchestrations</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Orchestration Name</th><th>Previous Status</th><th>Current Status</th></tr>");
            }
            foreach (ManagementObject inst in searchOrch.Get())
            {
                sb.AppendLine("<tr><td style=\"width:50px\">");
                sb.AppendLine(b.ToString());
                sb.AppendLine("</td><td style=\"width:600px\">");
                sb.AppendLine(inst["Name"].ToString());
                sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                if (inst["OrchestrationStatus"].ToString() == "1") { sb.AppendLine("Unbound"); }
                if (inst["OrchestrationStatus"].ToString() == "2") { sb.AppendLine("UnEnlisted"); }
                if (inst["OrchestrationStatus"].ToString() == "3") { sb.AppendLine("Stopped"); }
                sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                if (inst["OrchestrationStatus"].ToString() == "1") { sb.AppendLine("Unbound"); }
                if (inst["OrchestrationStatus"].ToString() == "2") { sb.AppendLine("UnEnlisted"); }
                if (inst["OrchestrationStatus"].ToString() == "3") { sb.AppendLine("Stopped"); }
                sb.AppendLine("</td></tr>");
                b++;
            }
            int orch = b;
            bool orchflag = true;
            foreach (string record in OrchestrationStatus)
            {
                foreach (ManagementObject inst in searchOrch.Get())
                {
                    if (record.Split(',')[0] == inst["Name"].ToString())
                    {
                        orchflag = false;
                    }
                }
                if (orchflag)
                {
                    sb.AppendLine("<tr><td style=\"width:50px\">");
                    sb.AppendLine(orch.ToString());
                    sb.AppendLine("</td><td style=\"width:600px\">");
                    sb.AppendLine(record.Split(',')[0]);
                    sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine(record.Split(',')[1]);
                    sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine("Started");
                    sb.AppendLine("</td><tr>");
                    orch++;
                }
                orchflag = true;
            }
            if (ConfigurationManager.AppSettings["FullReport"].ToString() == "Yes")
            {
                if (nNumOrch == 0 && OrchestrationStatus.Count == 0)
                {
                    sb.AppendLine("</table><h4 style=\"color:#6495ED\">Status Of Orchestrations</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Orchestration Name</th><th>Previous Status</th><th>Current Status</th></tr>");
                }
                ManagementObjectSearcher searchOrchFull = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_Orchestration where OrchestrationStatus = '4'", enumOptions);
                int orchFull = orch;
                int nNumOrchFull = searchOrchFull.Get().Count;
                ArrayList OrchNameList = new ArrayList();
                foreach (string record in OrchestrationStatus)
                {
                    OrchNameList.Add(record.Split(',')[0]);
                }
                if (nNumOrchFull > 0)
                {
                    foreach (ManagementObject inst in searchOrchFull.Get())
                    {
                        if (!(OrchNameList.Contains(inst["Name"].ToString())))
                        {
                            sb.AppendLine("<tr><td style=\"width:50px\">");
                            sb.AppendLine(orchFull.ToString());
                            sb.AppendLine("</td><td style=\"width:600px\">");
                            sb.AppendLine(inst["Name"].ToString());
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Started");
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Started");
                            sb.AppendLine("</td><tr>");
                            orchFull++;
                        }
                    }
                }
            }
            ManagementObjectSearcher searchHost = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_HostInstance where HostType=1 and ServiceState <> '4'", enumOptions);
            int k = 1;
            int nNumHost = searchHost.Get().Count;
            if (nNumHost > 0 || HostStatus.Count > 0)
            {
                sb.AppendLine("</table><h4 style=\"color:#6495ED\">Status Of Host Instances</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Host Instance Name</th><th>Previous Status</th><th>Current Status</th></tr>");
            }
            foreach (ManagementObject inst in searchHost.Get())
            {
                sb.AppendLine("<tr><td style=\"width:50px\">");
                sb.AppendLine(k.ToString());
                sb.AppendLine("</td><td style=\"width:600px\">");
                sb.AppendLine(inst["HostName"].ToString());
                sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">Stopped</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">Stopped</td></tr>");
                k++;
            }
            int hst = k;
            bool hstflag = true;
            foreach (string record in HostStatus)
            {
                foreach (ManagementObject inst in searchHost.Get())
                {
                    if (record == inst["HostName"].ToString())
                    {
                        hstflag = false;
                    }
                }
                if (hstflag)
                {
                    sb.AppendLine("<tr><td style=\"width:50px\">");
                    sb.AppendLine(hst.ToString());
                    sb.AppendLine("</td><td style=\"width:600px\">");
                    sb.AppendLine(record);
                    sb.AppendLine("</td><td style=\"background-color:#FF0000;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine("Stopped</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                    sb.AppendLine("Running");
                    sb.AppendLine("</td><tr>");
                    hst++;
                }
                hstflag = true;
            }
            if (ConfigurationManager.AppSettings["FullReport"].ToString() == "Yes")
            {
                if (nNumHost == 0 && HostStatus.Count == 0)
                {
                    sb.AppendLine("</table><h4 style=\"color:#6495ED\">Status Of Host Instances</h4><table style=\"width:900px\"><tr><th>S.No</th><th>Host Instance Name</th><th>Previous Status</th><th>Current Status</th></tr>");
                }
                ManagementObjectSearcher searchHostFull = new ManagementObjectSearcher(ConfigurationManager.AppSettings["BizTalkServer"].ToString(), "Select * from MSBTS_HostInstance where HostType=1 and ServiceState = '4'", enumOptions);
                int hstFull = hst;
                int nNumhstFull = searchHostFull.Get().Count;
                if (nNumhstFull > 0)
                {
                    foreach (ManagementObject inst in searchHostFull.Get())
                    {
                        if (!(HostStatus.Contains(inst["HostName"].ToString())))
                        {
                            sb.AppendLine("<tr><td style=\"width:50px\">");
                            sb.AppendLine(hstFull.ToString());
                            sb.AppendLine("</td><td style=\"width:600px\">");
                            sb.AppendLine(inst["HostName"].ToString());
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Running");
                            sb.AppendLine("</td><td style=\"background-color:green;color:white;width:120px;text-align:center;\">");
                            sb.AppendLine("Running");
                            sb.AppendLine("</td><tr>");
                            hstFull++;
                        }
                    }
                }
            }
            string strTotalWQL = string.Format("SELECT * FROM MSBTS_ServiceInstance where ServiceStatus = 4");
            ManagementObjectSearcher searcherGetServiceName = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strTotalWQL), null);
            int nNumGetServiceName = searcherGetServiceName.Get().Count;
            int r = 1;
            if (nNumGetServiceName > 0)
            {
                sb.AppendLine("</table><h3 style=\"color:#B22222\">Please find below the list of Resumable Failed Messages</h3><table style=\"width:900px\"><tr><th>S.No</th><th>ServiceName</th><th>Error Description</th><th>Count</th></tr>");

            }
            foreach (ManagementObject objSuspendList in searcherGetServiceName.Get())
            {
                {
                    if (StoreData(objSuspendList["ServiceName"].ToString(), objSuspendList["ErrorDescription"].ToString()))
                    {
                        sb.AppendLine("<tr><td style=\"width:30px\">");
                        sb.AppendLine(r.ToString());
                        sb.AppendLine("</td><td style=\"width:200px\">");
                        sb.AppendLine(objSuspendList["ServiceName"].ToString());
                        sb.AppendLine("</td><td style=\"width:600px\">");
                        sb.AppendLine(objSuspendList["ErrorDescription"].ToString());
                        sb.AppendLine("</td><td style=\"width:70px\">");
                        string ErrorDes = objSuspendList["ErrorDescription"].ToString();
                        //string queryErrDesc = Before(ErrorDes, "at System").Trim();
                        string queryErrDesc;
                        if (ErrorDes.IndexOf("\n") != -1)
                        {
                            queryErrDesc = ErrorDes.Substring(0, ErrorDes.IndexOf("\n")).Trim();
                        }
                        else
                        {
                            queryErrDesc = ErrorDes.Trim();
                        }
                        try
                        {
                            string strSvcGetCount = string.Format("SELECT * FROM MSBTS_ServiceInstance where ServiceName = \"{0}\" AND ErrorDescription LIKE '%{1}%'", objSuspendList["ServiceName"], queryErrDesc);
                            //string strSvcGetCount = string.Format("SELECT * FROM MSBTS_ServiceInstance where ServiceName = \"{0}\" AND ErrorID = \"{1}\"", objSuspendList["ServiceName"], objSuspendList["ErrorID"]);
                            ManagementObjectSearcher searcherGetServiceCount = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strSvcGetCount), null);
                            int nNumGetCount = searcherGetServiceCount.Get().Count;
                            sb.AppendLine(nNumGetCount.ToString());
                            sb.AppendLine("</td></tr>");
                            r++;
                        }
                        catch
                        {
                            sb.AppendLine("UnKnown");
                            sb.AppendLine("</td></tr>");
                            r++;
                        }
                    }
                }
            }
            /* Added for Non-resumble */
            StoreServiceName.Clear();
            string strTotalWQL1 = string.Format("SELECT * FROM MSBTS_ServiceInstance where ServiceStatus = 32");
            ManagementObjectSearcher searcherGetServiceName_NonRes = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strTotalWQL1), null);
            int nNumGetServiceName1 = searcherGetServiceName_NonRes.Get().Count;
            int r1 = 1;
            if (nNumGetServiceName1 > 0)
            {
                sb.AppendLine("</table><h3 style=\"color:#B22222\">Please find below the list of Non-Resumable Failed Messages</h3><table style=\"width:900px\"><tr><th>S.No</th><th>ServiceName</th><th>Error Description</th><th>Count</th></tr>");

            }
            foreach (ManagementObject objSuspendList1 in searcherGetServiceName_NonRes.Get())
            {
                {
                    string errDescription = String.Empty;
                    try
                    {
                        errDescription = objSuspendList1["ErrorDescription"].ToString();
                    }
                    catch
                    {
                        errDescription = "Cannot Retrieve Error Description. Please check the admin Console for details.";
                    }
                    if (StoreData(objSuspendList1["ServiceName"].ToString(), errDescription))
                    {
                        sb.AppendLine("<tr><td style=\"width:30px\">");
                        sb.AppendLine(r1.ToString());
                        sb.AppendLine("</td><td style=\"width:200px\">");
                        sb.AppendLine(objSuspendList1["ServiceName"].ToString());
                        sb.AppendLine("</td><td style=\"width:600px\">");
                        sb.AppendLine(errDescription);
                        sb.AppendLine("</td><td style=\"width:70px\">");
                        string ErrorDes = errDescription;
                        //string queryErrDesc = Before(ErrorDes, "at System").Trim();
                        string queryErrDesc;
                        if (ErrorDes.IndexOf("\n") != -1)
                        {
                            queryErrDesc = ErrorDes.Substring(0, ErrorDes.IndexOf("\n")).Trim();
                        }
                        else
                        {
                            queryErrDesc = ErrorDes.Trim();
                        }
                        try
                        {
                            errDescription = objSuspendList1["ErrorDescription"].ToString();
                            string strSvcGetCount = string.Format("SELECT * FROM MSBTS_ServiceInstance where ServiceName = \"{0}\" AND ErrorDescription LIKE '%{1}%'", objSuspendList1["ServiceName"], queryErrDesc);
                            //string strSvcGetCount = string.Format("SELECT * FROM MSBTS_ServiceInstance where ServiceName = \"{0}\" AND ErrorID = \"{1}\"", objSuspendList["ServiceName"], objSuspendList["ErrorID"]);
                            ManagementObjectSearcher searcherGetServiceCount = new ManagementObjectSearcher(new ManagementScope(ConfigurationManager.AppSettings["BizTalkServer"].ToString()), new WqlObjectQuery(strSvcGetCount), null);
                            int nNumGetCount = searcherGetServiceCount.Get().Count;
                            sb.AppendLine(nNumGetCount.ToString());
                            sb.AppendLine("</td></tr>");
                            r1++;
                        }
                        catch
                        {
                            sb.AppendLine("UnKnown");
                            sb.AppendLine("</td></tr>");
                            r1++;
                        }
                    }
                }
            }
            /*End here for Non-reumable */
            sb.AppendLine("</table><br /><div id=\"footer\">Copyright &copy; All Rights Reserved</div></body></html>");
            string s = sb.ToString();
            byte[] data = Encoding.ASCII.GetBytes(s);
            return data;
        }
        public static void SendFailureReport()
        {
            try
            {
                string server = ConfigurationManager.AppSettings["SMTPServer"].ToString();
                string portnum = ConfigurationManager.AppSettings["PortNumber"].ToString();
                string frmAdd = ConfigurationManager.AppSettings["FromAddress"].ToString();
                string passwrd = ConfigurationManager.AppSettings["PassWord"].ToString();
                string toAdd = ConfigurationManager.AppSettings["ToAddress"].ToString();
                string ccAdd = ConfigurationManager.AppSettings["CCAddress"].ToString();
                string subject = ConfigurationManager.AppSettings["Subject"].ToString();
                byte[] data = GetData();
                SmtpClient client = new SmtpClient(server);
                MailMessage Msg = new MailMessage();
                if (portnum.Length > 0)
                {
                    client.Port = Int32.Parse(portnum);
                }
                string[] listfrmAdd = frmAdd.Split(',');
                foreach (string frm in listfrmAdd)
                {
                    if (frm.Length > 0)
                    {
                        Msg.From = new MailAddress(frm);
                    }
                }
                string[] listToAdd = toAdd.Split(',');
                foreach (string to in listToAdd)
                {
                    if (to.Length > 0)
                    {
                        Msg.To.Add(to);
                    }
                }
                string[] listCCAdd = ccAdd.Split(',');
                foreach (string cc in listCCAdd)
                {
                    if (cc.Length > 0)
                    {
                        Msg.CC.Add(cc);
                    }
                }
                MemoryStream ms = new MemoryStream(data);
                ContentType ct = new ContentType(MediaTypeNames.Text.Html);
                Attachment attach = new Attachment(ms, ct);
                Msg.Attachments.Add(attach);
                attach.ContentDisposition.FileName = "BizTalkReport.html";
                Msg.Subject = subject;
                Msg.Body = "Please find the Automated Health Report Attached in the Mail";
                if (passwrd.Length > 0)
                {
                    client.Credentials = new System.Net.NetworkCredential(frmAdd, passwrd);
                }
                else
                {
                    client.UseDefaultCredentials = true;
                }
                client.Send(Msg);
                ms.Close();
                Console.WriteLine("Mail Sent Succesfully");
                //Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Mail Sending Failed" + ex.Message);
                Console.ReadLine();
            }
        }
        public static bool StoreData(string SvcName, string ErrDes)
        {
            if ((StoreServiceName.Contains(SvcName)) && (StoreErrorDescription.Contains(ErrDes)))
            {
                return false;
            }
            else
            {
                StoreServiceName.Add(SvcName);
                StoreErrorDescription.Add(ErrDes);
                return true;
            }
        }
        public static string Before(string ErrDesc, string ToRemove)
        {
            int posA = ErrDesc.IndexOf(ToRemove);
            if (posA == -1)
            {
                return "";
            }
            return ErrDesc.Substring(0, posA);
        }

        //Code for CPU Counter
        public static float getCPUCounter()
        {
            PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            float firstValue = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            float cpuUsage = cpuCounter.NextValue();
            return cpuUsage;
        }
    }
}






